<template>
  <div>
    <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="pyjm" label="" class="">
          <a-input v-model:value="formState.pyjm" class="w-64" placeholder="药品名称/助记码/药品编号/单号" />
        </a-form-item>
        <a-form-item name="dateRange" label="制单日期">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD " value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="状态" class="w-[330px]">
          <a-select v-model:value="formState.status" placeholder="请选择" allow-clear mode="multiple" :max-tag-count="2">
            <a-select-option key="0">待审核</a-select-option>
            <a-select-option key="1">待出库</a-select-option>
            <a-select-option key="2">待入库</a-select-option>
            <a-select-option key="3">已入库</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex">
        <a-button class="mb-2" type="primary" @click="onAdd"> 新增 </a-button>
      </div>
      <BaseTable
        :data-source="tableData"
        fill
        :loading="loading"
        :scroll="{ x: 1800 }"
        column-code="000306"
        :pagination="pagination"
        @change="onPageChange"
        @expand="onShowChild"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'status'">
            <!-- 0：待审核 1：待出库 2：待入库 3：已入库 -->
            <a-tag v-if="record.status === '1'" color="red">待出库</a-tag>
            <a-tag v-else-if="record.status === '2'" color="green">待入库</a-tag>
            <a-tag v-else-if="record.status === '3'" color="green">已入库</a-tag>
            <a-tag v-else color="blue">待审核</a-tag>
          </template>
          <template v-if="column.dataIndex === 'applyDh'">
            <PopoverTable :config="detailConfig" :params="{ ckbh: record.storeCode, applyDh: record.applyDh }" :width="1500">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'drugName'">
                  <MedicineInfo :value="{ mc: popRecord.drugName, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
              </template>
              {{ record.applyDh }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" :disabled="record.status !== '0'" @click="onDetail(record)">明细</a-button>
              <a-button v-if="record.status === '1'" type="link" size="small" @click="onClickStatus(record)">撤审</a-button>
              <a-button v-else type="link" size="small" :disabled="record.status !== '0'" @click="saveConsumeStatus(record, '1')">审核</a-button>
              <BaseButton confirm-text="是否确认入库?" type="link" size="small" :disabled="record.status !== '2'" @click="confirmInStorage(record)">
                确认入库
              </BaseButton>
              <TableMoreButton>
                <a-button type="link" size="small" :disabled="record.status !== '0'" @click="onEditOpen(record)">修改</a-button>
                <BaseButton
                  confirm-text="是否作废此申领单?"
                  type="text"
                  danger
                  size="small"
                  :disabled="record.status !== '0'"
                  @click="saveConsumeStatus(record, '4')"
                >
                  作废
                </BaseButton>
                <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button>
              </TableMoreButton>
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <Edit v-model:open="editOpen" :title="editTitle" :row-data="rowData" @success="onSuceess" />
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import useUserStore from '@/store/user'
import Edit from './Edit'

const { empId } = useUserStore()
const editOpen = ref(false)
const editTitle = ref('')
const rowData = ref({})
const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const userKsdm = ref('')
const formState = ref({
  ckbh: '',
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  pyjm: ''
})

const detailConfig = ref({
  url: '/drugStorage/consume/getKcApplyDetailList',
  columnCode: '000314',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})
const onAdd = () => {
  rowData.value = {}
  editOpen.value = true
  editTitle.value = '新增申领单'
}
const onSuceess = (e) => {
  getData()
  router.push({
    path: '/drug-consume/drug-apply/detail',
    query: {
      dh: e.applyDh
    }
  })
}
const { loading, tableData, getData, pagination } = useTable({
  url: '/drugStorage/consume/getKcApplyEntityList',
  immediate: false,
  formatParams: () => {
    return {
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      pyjm: formState.value.pyjm,
      ckbh: formState.value.ckbh,
      status: formState.value.status,
      materialType: route.query?.routerType || undefined // 防疫物资
    }
  }
})

const getDepartInfo = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  formState.value.ckbh = res.data?.ksdm
  getData()
}

const onEditOpen = (record) => {
  rowData.value = { ...record }
  editOpen.value = true
  editTitle.value = '修改申领单'
}
const saveConsumeStatus = async (record, type) => {
  const formData = {
    id: record.id,
    storeCode: record.storeCode,
    status: type
  }
  const res = await post('/drugStorage/consume/doSaveKcApply', formData)
  if (res.code !== 0) return message.error(res.msg || type === '0' ? '审核失败' : '作废失败')
  message.success(res.msg)
  getData()
}

// 撤销
const onClickStatus = async (row) => {
  const res = await post('/drugStorage/consume/doKcApplyCs', { id: row.id })
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  getData()
}

const confirmInStorage = async (record) => {
  const res = await post('/drugStorage/consume/applyDoKcConsumeStorage', {
    applyDh: record.applyDh,
    ckbh: userKsdm.value
  })
  if (res.code !== 0) return message.error(res.msg || '入库失败')
  message.success(res.msg)
  getData()
}
const onDetail = (record) => {
  router.push({
    path: '/drug-consume/drug-apply/detail',
    query: {
      dh: record.applyDh
    }
  })
}

const onPrint = async (row) => {
  const { code, msg, data } = await post('/drugStorage/psiform/printKcApply', { applyDh: row.applyDh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
onMounted(() => {
  getDepartInfo()
})
</script>
